﻿/* ----------------------------------------------------------------------------------------------------------------------
 * SectionManager
 * -----------------------------------------------------------------------------------------------------------------------
 */

/*
   嵌入标签 :
		
	    [字体]
		[Embed(source='/../media/fonts/Abduction.ttf', embedAsCFF='false', fontName/fontFamily='Abduction')]
		
		[XML]
		[Embed(source = "colonist_32_32.xml",mimeType = "application/octet-stream")] 
 */ 	
 	
/*
    ＃ 片段资源必须在游戏前加载或直接嵌入.
 */
	
/*	
    片段XML使用说明 : 
			
			Section :
					0. type          -  类型
					1. name          -  片段名称
					2. def           -  资源定义
					3. x             -  X轴偏移量    （左上角为起点，实体为中心）
					4. y             -  Y轴偏移量    （左上角为起点，实体为中心）
					5. real          -  碰撞矩形      ＃ 非必要

				Action :
					1. name          -  动作名称
					2. reversed      -  翻转（左右）  ＃ 非必要
					3. frameRate     -  fps           ＃ 非必要
					
						
			<section type="SWF">
					<name>      colonist_32_32                                </name>
					<def>       colonist_32_32                                 </def>
					<x>         -16                                              </x>
					<y>         -15.5                                            </y>
					<real       x="11" y="2" width="10" height="29"/>

					<action     name="right_stand"                                  >   1      </action>
					<action     name="right_jump"                     frameRate="7" >   2-3    </action>
					<action     name="right_run"                      frameRate="10">   4-9    </action>
					<action     name="left_stand"   reversed="true"                 >   1      </action>
					<action     name="left_jump"    reversed="true"   frameRate="7" >   2-3    </action>
					<action     name="left_run"     reversed="true"   frameRate="10">   4-9    </action>
			</section>
 */
	
package pure.engine.renderer.sections 
{
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	import pure.debug.Logger;
	import pure.engine.events.SectionEvent;
	import pure.engine.core.SystemManager;
	import pure.engine.Multiple;
	import pure.engine.core.ns_despair;
	
	use namespace ns_despair;
	
	/**
	 * @internal
	 * 
	 * 片段管理器
	 * 
	 * @author ＃Pure
	 * 
	 */
public class SectionManager 
{
	
	
	ns_despair static var m_sectionMap:Dictionary = new Dictionary();
	
	ns_despair static var m_numSection:int;

	
	
	/**
	 * 添加片段数据
	 * 
	 * @param data
	 **/
	ns_despair static function registerSections(data:XML):void 
	{
		var name:String, type:String, source:String, actionName:String, actionData:String;
		var x:Number, y:Number, width:Number, height:Number;
		var reversed:Boolean;
		var realRect:Rectangle;
		var section:Section;
		var node:XML;
		var lenS:int, lenA:int, frameRate:int;
		
		lenS = data.section.length();
		while (--lenS > -1)
		{
			node = data.section[lenS];
			
			type = node.@type;
			name = node.name;
			source = node.def;
			
			if (name == null || name == '')
			{
				throw new Error("[SectionManager] - ＃registerSections - Section don't have a null name!");
			}
			
			// 任何实体都有一定真实存在体积.
			x      = node.real.@x;
			y      = node.real.@y;
			width  = node.real.@width;
			height = node.real.@height;
			realRect = new Rectangle(x, y, width + 0.001, height + 0.001);
			
			x = node.x;
			y = node.y;
			
			// IMAGE型
			if (type=='IMG') 
			{
				section = new ImageSection(name, source, x, y, node.width, node.height, realRect);
			}
			
			// SWF型
			else if (type=='SWF')
			{
				section = new MovieClipSection(name, source, x, y, realRect);
			}

			else
			{
				throw new Error('SectionManager - ＃addSection - 文件类型 ('+type+') 错误 : ' + type);
			}
			
			lenA = node.action.length();
			while (--lenA > -1)
			{
				actionName = node.action[lenA].@name;
				actionData = node.action[lenA];
				reversed = Boolean(node.action[lenA].@reversed == 'true');
				frameRate = parseInt(node.action[lenA].@frameRate);
				section.addAction(actionName, actionData, reversed, frameRate);
			}
			
			_addSectionToList(name,section);
		}
	}

	
	ns_despair static function makeSectionBySWF(name:String, SWF:MovieClip, params:Array):void
	{
		var length:int = SWF.totalFrames;
		var width:Number = SWF.width;
		var height:Number = SWF.height;
		var section:MovieClipSection;
		var actionData:*;
		var len:int,i:int;
		
		params   =  (params.length) ? params : ([{'name':'despair','data':'1-'+length.toString(),'frameRate':24}]);
		section  =  new MovieClipSection(name,SWF, -0.5 * width, -0.5 * height, new Rectangle(0,0,width,height));
		len      =  params.length;
		
		for (i = 0; i < len; i++)
		{
			actionData = params[i];
			section.addAction(actionData.name, actionData.data , actionData.reversed, actionData.frameRate);
		}

		_addSectionToList(name,section);
	}
	

	//ns_despair static function makeSectionBySWF(name:String, Image:BitmapData, frameRate:int, data:String):void
	//{
		//var length:int = SWF.totalFrames;
		//var width:Number = SWF.width;
		//var height:Number = SWF.height;
		//
		//data = (data != null)? data : "1-" + length;
		//
		//var section:MovieClipSection = new MovieClipSection(name,SWF, -0.5 * width, -0.5 * height, new Rectangle(0,0,width,height));
		//section.addAction("despair", data , false, frameRate);
		//
		//m_sectionMap[name] = section;
	//}
	
	
	/**
	 * 获取片段
	 * 
	 * @param sectionName
	 * 
	 * @see AnimeRenderer - ＃_setSection
	 **/
	ns_despair static function getSection(sectionName:String):Section 
	{
		if (!m_sectionMap[sectionName])
		{
			Logger.reportError('SectionManager','getSection','Section :（'+sectionName+'） 不存在.');
		}
		
		return m_sectionMap[sectionName];
	}
	
	
	
	private static function _addSectionToList(name:String,section:Section):void
	{
		if(m_sectionMap[name])
		{
			Logger.reportWarning('SectionManager', '_addSectionToList','Section (' + name + ') 被同名覆盖 !!');
		}
		else
		{
			Logger.reportMessage('SectionManager', 'Section (' + name + ') 注册完成.');
		}
		m_sectionMap[name] = section;
		m_numSection++;
		
		Multiple.m_notifier.dispatchEvent(new SectionEvent(SectionEvent.SECTION_REGISTERED, name));
	}
	
	
}

}